﻿using Unity.Collections;
using Unity.Entities;
using Unity.Jobs.LowLevel.Unsafe;
using UnityEngine;
using Random = Unity.Mathematics.Random;

namespace Tutorial3_Jobs
{
    /*
     *TLS : Thread Local Storage : 子线程访问自己的内容，以免造成竞争
     */
    [UpdateInGroup(typeof(Tutorial03SystemGroup))]
    public partial struct Tls_JobSystem : ISystem
    {
        private NativeArray<Random> _randomsArray;
        
        public void OnCreate(ref SystemState state)
        {
            // 根据线程数量，创建不同的RD
            // 让不同的线程用各自自己的RD，避免公用RD造成竞争
            int maxJobThreadCount = JobsUtility.MaxJobThreadCount;
            _randomsArray = new NativeArray<Random>(maxJobThreadCount, Allocator.Persistent);
            for (int i = 0; i < maxJobThreadCount; i++)
            {
                _randomsArray[i] = Random.CreateFromIndex((uint)i);
            }
        }

        public void OnUpdate(ref SystemState state)
        {
            TLS_Job job = new TLS_Job()
            {
                Randoms = _randomsArray,
                deltaTime = SystemAPI.Time.DeltaTime
            };
            job.ScheduleParallel();
        }

        public void OnDestroy(ref SystemState state)
        {
            _randomsArray.Dispose();
        }
    }
}